<template>
  <div class="login-box">
    <base-header></base-header>
    <div class="nng-login">
      <div :style="{ 'padding-left': 10 + 'px' }">
        <span class="login-text">登录</span>
        <span> / </span>
        <span class="register">
            <router-link to="/personal-register">注册</router-link> 
        </span>
      </div>
      
      <div class="form-box">
        <template v-if="changeLogin === true">
          <el-form ref="LoginForm" :rules="rules" :model="LoginForm">
            <el-form-item class="region" required>
              <el-form-item class="region-left">
                <el-select v-model="LoginForm.region" placeholder="+86" clearable filterable>
                  <el-option v-for="item in phoneAreaList" :key="item.id" :label="'+'+item.areanum" :value="item.areanum"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="phone" class="region-right" key="pwdPhone">
                <el-input v-model="LoginForm.phone" placeholder="请输入手机号"></el-input>
              </el-form-item>
            </el-form-item>
            <el-form-item prop="password" key="loginPWD">
              <el-input type="password" v-model.trim="LoginForm.password" autocomplete="off" placeholder="请输入平台登录密码" show-password></el-input>
            </el-form-item>
            <el-form-item key="btnSumbit">
              <el-button type="primary" :loading="loading" class="login-btn" @click="submitForm('LoginForm')">登录</el-button>
            </el-form-item>
          </el-form>
        </template>

        <template v-else>
          <el-form ref="codeLoginForm" :rules="rules" :model="codeLoginForm">
            <el-form-item class="region" required>
              <el-form-item class="region-left">
                <el-select v-model="codeLoginForm.region" placeholder="+86" clearable filterable>
                  <el-option v-for="item in phoneAreaList" :key="item.id" :label="'+'+item.areanum" :value="item.areanum"></el-option>
                </el-select>
                
              </el-form-item>
              <el-form-item prop="phone" class="region-right" key="codePhone">
                <el-input v-model="codeLoginForm.phone" placeholder="请输入手机号"></el-input>
              </el-form-item>
            </el-form-item>
            <el-form-item prop="code" key="phoneCode">
              <el-input v-model="codeLoginForm.code" placeholder="请输入短信验证码"></el-input>
              <el-button class="send-code" @click="sendCode" :disabled="forbidenClick">发送验证码</el-button>
            </el-form-item>
            <el-form-item key="codeSumbit">
              <el-button type="primary" :loading="loading" class="login-btn" @click="codeSubmit('codeLoginForm')">登录</el-button>
            </el-form-item>
          </el-form>
        </template>
        <div class="out-login">
          <router-link to="/resetPwd">忘记密码</router-link>
          <div @click="changeLogin = !changeLogin">
            <span class="changeLogin" v-if="changeLogin">使用手机验证码登录</span>
            <span class="changeLogin" v-else>使用手机号+密码登录</span>
          </div>
        </div>
      </div>
    </div>
    <base-footer></base-footer>
    <base-picture></base-picture>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { login, codeLogin, sendCodeRequest, areaList } from 'api/index'
// import { getUserRole } from 'api/UserController/UserController'
import BaseHeader from '@/components/base/header/Header'
import BaseFooter from '@/components/base/footer/Footer'
import BasePicture from '@/components/base/picture/Picture'
const DEVICE_CODE = "device00001111"
const DEVICE_TYPE = 3
const APP_ID = 'nng0031'
export default {
  name: 'Login',
  data () {
    //自定义手机号验证
    const checkPhone = (rule, value, callback) => {
      if (value == "") {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^[0-9]*$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    }
    //自定义密码验证
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入平台登录密码"));
      } else {
        // var reg1 = /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[a-zA-Z0-9]{8}$/;  不包含特殊字符
        // /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*])[\da-zA-Z~!@#$%^&*]{8,}$/
        var reg1 = /^(?=.*?[0-9])(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[~!@#$%^&*])[0-9A-Za-z~!@#$%^&*)]{8,}$/;
        if (reg1.test(value)) {
          callback();
        }else {
          return callback(new Error("密码由8位数大小写字母、数字和特殊字符组成"));
        }
      }
    };
    // 验证验证码
    const checkCode = (rule, value, callback) => {
        if(value == "") {
            return callback(new Error("请输入验证码"));
        }else{
            const reg1 = /^[0-9]{6}$/
            if (!reg1.test(value)){
                return callback(new Error("验证码必须为6位数"))
            }else{
                callback();
            }
        }
    }
    return {
      changeLogin: true,
      forbidenClick: false,
      loading: false,
      LoginForm: {
        region: '',
        phone: '',
        password: ''
      },
      codeLoginForm: {
        region: '',
        phone: '',
        code: ''
      },
      rules: {
        phone: [
          { validator: checkPhone, required: true, trigger: 'change' }
        ],
        password: [
          { validator: validatePass, required: true, trigger: 'change' }
        ],
        code: [
          { required: true, validator: checkCode, trigger: 'change'}
        ],
      },
      phoneAreaList: []
    }
  },
  components: {
    BaseHeader,
    BaseFooter,
    BasePicture
  },
  methods: {
    // ...mapMutations([
    //   'saveUserName',
    //   'saveToken',
    //   'saveUserId'
    // ]),
    ...mapMutations([
      'saveUserName',
      'saveUserInfo',
      'getUserRole'
    ]),
    // keyboardlogin(formName){
    //   this.submitForm(formName)
    // },
    // 密码登录
    submitForm(formName){
      this.$refs[formName].validate(valid => {
        if(valid){
          this.loading = true
          var params = {
            userName: this.LoginForm.phone,
            pwd: this.LoginForm.password,
            deviceCode: DEVICE_CODE,
            deviceType: DEVICE_TYPE,
            appId: APP_ID
          }
          login(params).then(res => {
            console.log(res)
            if(res.response_code == 0){
              console.log(res.result.token)
              // 保存用户名
              this.saveUserName(this.LoginForm.phone)
              // 保存token
              // window.localStorage.setItem('token',res.result.token)
              //this.saveToken(res.result.token)
              // 保存user_id
              // window.localStorage.setItem('userId',res.result.user_id)
              //this.saveUserId(res.result.user_id)
              // 保存用户信息对象
              this.saveUserInfo(res.result)
              // getUserRole(res.result.user_id).then(res => {
              //   if(res.resultCode == 1){
              //     this.getUserRole(res.data)
              //   }
              // })
              this.$router.push({ name: 'Home' })
            }else{
              this.$message.error(res.reason)
              this.loading = false
            }
          })
          
        }else{
          console.log('error submit!!');
          return false
        }
      })
    },
    // 验证码登录
    codeSubmit(formName){
      this.$refs[formName].validate(valid => {
        if(valid){
          this.loading = true
          var params = {
            phone: this.codeLoginForm.phone,
            code: this.codeLoginForm.code,
            deviceCode: DEVICE_CODE,
            deviceType: DEVICE_TYPE,
            appId: APP_ID
          }
          console.log(params)
          codeLogin(params).then(res => {
            console.log(res)
            if(res.response_code == 0){
              // 保存用户名
              this.saveUserName(this.codeLoginForm.phone)
              // 保存token
              // window.localStorage.setItem('token',res.result.token)
              // this.saveToken(res.result.token)
              // 保存userId
              // window.localStorage.setItem('userId',res.result.user_id)
              // this.saveUserId(res.result.user_id)
              // 保存用户信息对象
              this.saveUserInfo(res.result)
              // getUserRole(res.result.user_id).then(res => {
              //   if(res.resultCode == 1){
              //     this.getUserRole(res.data)
              //     this.$router.push({ name: 'Home' })
              //   }
              // })
              this.$router.push({ name: 'Home' })
            }else{
              this.$message.error(res.reason)
              this.loading = false
            }
          })
        }
      })
    },
    
    sendCode(){ // 发送验证码
      // if(this.codeLoginForm.region == ''){
      //   this.codeLoginForm.region = '86'
      // }
      var params = {
        info: this.codeLoginForm.phone,
        method: 'phone',
        areaCode: this.codeLoginForm.region.toString() || '86'
      }
      
      sendCodeRequest(params).then(res => {
        console.log(res)
        if(res.response_code == 0){
          this.forbidenClick = true
            setTimeout(() => {
              this.forbidenClick = false
            }, 10000);
          }else{
            this.$message.error(res.reason)
          }
      })
      
    },

    // 获取区号列表
    getAreaList(){
      areaList().then(res => {
        console.log(res)
        res.result.area_code.unshift({ areanum: 86, cname: '中国大陆', ename: 'China', fee: 1 })
        this.phoneAreaList = res.result.area_code
      })
    }
  },
  created(){
    this.getAreaList()
  },
  computed: {
    
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/varible';
.login-box{
  height: 100%;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: #ffffff;
}
.nng-login{
  position: absolute;
  left: 83px;
  top: 50%;
  transform: translateY(-50%);
  .login-text{
    font-size: 15px;
    color:rgba(102,102,102,1);
  }
  .register{
    a{
      color: #bbbbbb;
    }
  }
  .form-box{
    padding-top: 55px;
    padding-left: 10px;
    padding-right: 10px;
    box-sizing: border-box;
    .login-btn{
      width: 108px;
      background:rgba(64,101,224,1);
    }
    .out-login{
      display: flex;
      justify-content: space-between;
      a{
        color:rgba(153,153,153,1);
        font-size: 10px;
      }
    }
    .changeLogin{
      color:rgba(102,102,102,1);
      font-size: 10px;
      cursor: pointer;
    }
    .send-code{
      margin-left: 10px;
      background: #36C2CF;
      color: #ffffff;
    }
  }
}

</style>
